<template>
    <div ref="chart" style="width: 100%;height:400px;"></div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import { onMounted, reactive, ref, watch } from 'vue';

type PropsType = {
    title: string,
    xdata?: string[],
    seriesdata?: number[]
}

const props = defineProps<PropsType>()

const chart = ref()
// 指定图表的配置项和数据
const option = reactive({
    title: {
        text: props.title
    },
    xAxis: {
        type: 'category',
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
        type: 'value'
    },
    series: [
        {
            data: [820, 932, 901, 934, 1290, 1330, 1320],
            type: 'line',
            smooth: true
        }
    ]
});

function initChart() {
    // 基于准备好的dom，初始化echarts实例
    const myChart = echarts.init(chart.value);
    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);
    // 自适应
    window.addEventListener('resize', () => {
        myChart.resize()
    })
}

watch([() => props.xdata, () => props.seriesdata], () => {
    if (props.xdata && props.seriesdata) {
        option.xAxis.data = props.xdata
        option.series[0].data = props.seriesdata
        initChart()
    }
}, { immediate: true })
</script>